﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Dos.ORM;
using GalaSoft.MvvmLight.Command;
using OfficeHelper.Model;
using OfficeHelper.Model.LongRuan;

namespace OfficeHelper.ViewModel.LongRuan
{
    public class LRIndexViewModel: OfficeHelpViewModelBase
    {

        public LRIndexViewModel()
        {
            SiteMenuConfigCommand = new RelayCommand(SiteMenuConfig);
            TreeSelectItemChangeCommand = new RelayCommand<object>(TreeSelectItemChangeMethod);
            ADDMenuCommand = new RelayCommand(ADDMenuMethod,()=>
            {    //为模块组 才可以选
                if (SelectNode!=null&&SelectNode.Data!=null&&SelectNode.Data.Type==1)
                {
                    return true;
                }
                return false;
            });
            ADDViewADDCommand = new RelayCommand(ADDViewADDMethod);


        }

        private string _Conn= "server=58.218.64.10,1440;database=LKJT_Base_1.4.8;uid=sa;pwd=longruan@123";

        public string ConnStr
        {
            get { return _Conn; }
            set
            {
                Set("ConnStr", ref _Conn, value);
            }
        }

        private ObservableCollection<T_WEBSITE> _WebSites;

        public ObservableCollection<T_WEBSITE> WebSites
        {
            get { return _WebSites; }
            set
            {
                Set("WebSites", ref _WebSites, value);
               
            }
        }

        private T_WEBSITE _ADDWebSite;

        public T_WEBSITE ADDWebSite
        {
            get { return _ADDWebSite; }
            set
            {
                Set("ADDWebSite", ref _ADDWebSite, value);
                if (_ADDWebSite!=null)
                {
                    ADDWebSiteTree(_ADDWebSite);
                }
            }
        }


        private Tree<T_WEBSITE_CONFIG> _ADDMenuTree;

        public Tree<T_WEBSITE_CONFIG> ADDMenuTree
        {
            get { return _ADDMenuTree; }
            set
            {
                Set("ADDMenuTree", ref _ADDMenuTree, value);
            }
        }

        private void ADDWebSiteTree(T_WEBSITE t_WEBSITE)
        {
            var config = dbSession.From<T_WEBSITE_CONFIG>().Where(x => x.WebSiteID == t_WEBSITE.ID && x.IsDel == "N"&&x.IsVisible=="Y").ToList(); ;
            Tree<T_WEBSITE_CONFIG> tree = new Tree<T_WEBSITE_CONFIG>();
            ADDTree(tree, config, 3);
            ADDMenuTree = tree;
        }


        

        public ICommand ADDViewADDCommand { get; set; }

        /// <summary>
        /// 添加菜单
        /// </summary>
        private void ADDViewADDMethod()
        {
            try
            {
                List<String> name = new List<string>();
                //首先获取选中的菜单
                SerarchTree(ADDMenuTree, name);
                ShowMessageBox(string.Join(",", name));
            }
            catch (Exception  ex)
            {
                ShowMessageBox(ex.ToString());
            }
           
        }

        //判断是否存在
        private T_WEBSITE_CONFIG ADDTest(T_WEBSITE_CONFIG  t_WEBSITE_CONFIG) {
            return dbSession.From<T_WEBSITE_CONFIG>().Where(x => x.WebSiteID == SelectWebSite.ID  && x.ModuleID == t_WEBSITE_CONFIG.ModuleID && x.IsDel == "N").First();
        }


        /// <summary>
        /// 编辑菜单
        /// </summary>
        private void EditMenu(T_WEBSITE_CONFIG newConfig, string parentNodeNo) {

           var data = dbSession.From<T_WEBSITE_CONFIG>().Where(x => x.IsDel == "N"&&x.ModuleID == newConfig.ModuleID 
            && x.ID != newConfig.ID && x.ModuleID != " " && x.WebSiteID == newConfig.WebSiteID).First();
            if (data != null)
            {
                string info = string.Format("菜单{0}{1}已存在,请删除后在添加!", data.Name, data.No);
                ShowMessageBox(info);
                return;
            }

            var old = dbSession.From<T_WEBSITE_CONFIG>().Where(x => x.ID == newConfig.ID).First();
            if (old!=null)
            {
                //查询子菜单
                var child = dbSession.From<T_WEBSITE_CONFIG>().Where(x => x.IsDel == "N" && x.WebSiteID == old.WebSiteID && x.No.StartsWith(old.No));
                string CurrentParentNode = (old.No.Length == 3) ? null : old.No.Substring(0, old.No.Length - 3);
                //如果不等于父节点ID
                if (CurrentParentNode != parentNodeNo) {
                    old.No = getNewNo(parentNodeNo, data.WebSiteID);
                    if (child!=null&&child.Count()>0)
                    {
                        
                    }

                }
            }

        }

        /// <summary>
        /// 获取新编码
        /// </summary>
        /// <param name="ParentNo">父级ID</param>
        /// <param name="WebSiteID">站点ID</param>
        /// <returns></returns>
        private string getNewNo(string ParentNo, string WebSiteID)
        {
            //Expression<Func<T_WEBSITE_CONFIG, bool>> rExp = (T_WEBSITE_CONFIG r) => r.WebSiteID == WebSiteID && r.IsDel == "N";
            ParentNo = ((ParentNo == null) ? "" : ParentNo);
            string maxNo= null;
            //rExp = ((!string.IsNullOrEmpty(ParentNo)) ? rExp.And((T_WEBSITE_CONFIG r) => r.No.StartsWith(ParentNo) && r.No.Length == ParentNo.Length + 3) : rExp.And((T_WEBSITE_CONFIG r) => r.No.Length == 3));
            if ((!string.IsNullOrEmpty(ParentNo)))
            {
                maxNo = dbSession.From<T_WEBSITE_CONFIG>().Where(r => r.WebSiteID == WebSiteID && r.IsDel == "N" && r.No.StartsWith(ParentNo) && r.No.Length == ParentNo.Length + 3).Select(x=>x.No.Max()).ToFirst<string>();
            }
            else {
                maxNo = dbSession.From<T_WEBSITE_CONFIG>().Where(r => r.WebSiteID == WebSiteID && r.IsDel == "N" && r.No.Length == 3).Select(x => x.No.Max()).ToFirst<string>();
            }
        
            if (maxNo != null)
            {
                ParentNo = FormatNo(maxNo);
            }
            else
            {
                ParentNo += "001";
            }
            return ParentNo;
        }

        private string FormatNo(string NowMaxNo)
        {
            int i = NowMaxNo.Length - 3;
            string startNo = NowMaxNo.Substring(0, i);
            string lastNo = NowMaxNo.Substring(i, 3);
            string no = (Convert.ToInt32(lastNo) + 1).ToString("000");
            return startNo + no;
        }


        private void SerarchTree(Tree<T_WEBSITE_CONFIG> tree, List<string> result) {
            if (tree.Data!=null&&tree.Data.IsCheck == true)
            {
                var test = ADDTest(tree.Data);
                if (test!=null)
                {
                    string info = string.Format("菜单{0}{1}已存在,请删除后在添加!",test.Name,test.No);
                    ShowMessageBox(info);
                    return;
                }
                result.Add(tree.Data.Name);
            }
            if (tree.Nodes!=null&&tree.Nodes.Count>0)
            {
                foreach (var item in tree.Nodes)
                {
                    SerarchTree(item,result);
                }
            }
        }

        private T_WEBSITE _SelectWebSite;

        public T_WEBSITE SelectWebSite
        {
            get { return _SelectWebSite; }
            set
            {
                Set("SelectWebSite", ref _SelectWebSite, value);
                if (_SelectWebSite != null)
                {
                    SelectMenuTree(_SelectWebSite);
                }
            }
        }

        private Tree<T_WEBSITE_CONFIG> _tree;

        public Tree<T_WEBSITE_CONFIG> MenuTree
        {
            get { return _tree; }
            set
            {
                Set("MenuTree", ref _tree, value);
            }
        }

        public ICommand ADDMenuCommand { get; set; }

        /// <summary>
        /// 增加菜单
        /// </summary>
        private void ADDMenuMethod()
        {
            View.LongRuan.LRMenuAddView lRMenuAddView = new View.LongRuan.LRMenuAddView();
            lRMenuAddView.ShowDialog();
        }



        public ICommand TreeSelectItemChangeCommand { get; set; }

        /// <summary>
        /// 选中节点更改时
        /// </summary>
        private void TreeSelectItemChangeMethod(object param)
        {
            var info = param as Tree<T_WEBSITE_CONFIG>;
            if (info != null)
            {
                SelectNode = info;
                //SelectNode = info;
                //Info = info.Data.Info.FullName;
            }
            else
            {
                SelectNode = null;
            }
        }

        private Tree<T_WEBSITE_CONFIG> _SelectNode;

        /// <summary>
        /// 选中的节点
        /// </summary>
        public Tree<T_WEBSITE_CONFIG> SelectNode
        {
            get { return _SelectNode; }
            set
            {
                Set("SelectNode", ref _SelectNode, value);
            }
        }

        private void SelectMenuTree(T_WEBSITE t_WEBSITE)
        {
            var config = dbSession.From<T_WEBSITE_CONFIG>().Where(x => x.WebSiteID == t_WEBSITE.ID && x.IsDel == "N").ToList(); ;
            Tree<T_WEBSITE_CONFIG> tree = new Tree<T_WEBSITE_CONFIG>();
            ADDTree(tree, config,3);
            MenuTree = tree;
        }

        private void ADDTree(Tree<T_WEBSITE_CONFIG> tree,List<T_WEBSITE_CONFIG> configs,int index)
        {
            var data = tree.Data;
            List<T_WEBSITE_CONFIG> list = null;
            if (data==null)
            {
                list = configs.Where(x => x.No.Length == index).OrderBy(x => x.Sort).ToList();
            }
            else
            {
                list = configs.Where(x => x.No.Length == index&&x.No.StartsWith(data.No)).OrderBy(x => x.Sort).ToList();
            }
             
            if (list != null)
            {
                foreach (var item in list)
                {
                    Tree<T_WEBSITE_CONFIG> child = new Tree<T_WEBSITE_CONFIG>();
                    child.Data = item;
                    tree.AddNode(child);
                    ADDTree(child, configs, index+3);
                }
            }
        }



        public ICommand SiteMenuConfigCommand { get; set; }

        DbSession dbSession;

        /// <summary>
        /// 站点菜单配置
        /// </summary>
        private void SiteMenuConfig()
        {
            try
            {
                dbSession = new DbSession(DatabaseType.SqlServer, ConnStr);

                var WEBSites = dbSession.From<T_WEBSITE>().OrderBy(x => x.Sort).ToList();
                //AddWebSites = WEBSites;
                ObservableCollection<T_WEBSITE> webSites = new ObservableCollection<T_WEBSITE>();
                if (WEBSites!=null)
                {
                    foreach (var item in WEBSites)
                    {
                        webSites.Add(item);
                    }

                }
                WebSites = webSites;


            }
            catch (Exception ex)
            {
                ShowMessageBox(ex.ToString());
            }


        }




    }
}
